﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.IO;
using System.Diagnostics;
using System.Collections;
using System.Net.Mail;

namespace template_dll
{
    public partial class ChildForm : Form
    {
        public ChildForm()
        {
            InitializeComponent();
        }
        //private struct Pharmflag { public int code; public bool fl; public int baseid; public int cityid; }
        private SqlConnection conn = new SqlConnection();
        private SqlConnection conf;
        private DataTable dt_ph_code;               //- коды аптек для прайсов
        private DataTable dt_ph_name;               //- для хранения названий аптек
        public DataTable dt_drugs;
        public DataTable dt_brand;
        public DataTable dt_suppl;
        public DataTable dt_pharm;
        public DataTable dt_drug_tmp;
        public DataTable dt_rep = new DataTable();
        public DataTable dt_email = new DataTable();
        //private Pharmflag[] phfl = new Pharmflag[] { };
        //private Pharmflag[] supfl = new Pharmflag[] { };
        private string folder = "";
        private const string namechcol = "Флаг";
        private Guid guid;
        private delegate void Deleg();
        private Deleg del;

        private int row_flag = 0;

        private string GetServ(string filename)
        {
            string str = "";
            using (StreamReader streamReader = new StreamReader(filename))
            {
                while (!streamReader.EndOfStream)
                {
                    str += streamReader.ReadLine();
                }
            }
            return str;
        }

        public static bool DisplayForm(System.Windows.Forms.Form theMDIParent)
        {
            ChildForm f = new ChildForm();
            f.MdiParent = theMDIParent;
            f.WindowState = FormWindowState.Maximized;
            f.Show();
            return true;
        }

        private Hashtable CheckExcellProcesses(Hashtable myHashtable)
        {
            Process[] AllProcesses = Process.GetProcessesByName("excel");
            int iCount = 0;
            foreach (Process ExcelProcess in AllProcesses)
            {
                myHashtable.Add(ExcelProcess.Id, iCount);
                iCount = iCount + 1;
            }
            return myHashtable;
        }
        private void DownloadPharmemail()
        {
            dt_email = null;
            dt_email = new DataTable();
            SqlCommand comm = conn.CreateCommand();
            comm.CommandText = "pas_PharmEmailSel";
            comm.CommandType = CommandType.StoredProcedure;
            if (conn.State == ConnectionState.Closed) conn.Open();
            dt_email.Load(comm.ExecuteReader());
            conn.Close();
        }

        private void KillExcel(Hashtable myHashtable)
        {
            Process[] AllProcesses = Process.GetProcessesByName("excel");
            foreach (Process ExcelProcess in AllProcesses)
            {
                if (myHashtable.ContainsKey(ExcelProcess.Id) == false)
                    ExcelProcess.Kill();
            }
            AllProcesses = null;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DrugsFilter.DrugsFilter f2 = new DrugsFilter.DrugsFilter();
            DrugsFilter.DrugsFilter.StorProcParam[] spp = new DrugsFilter.DrugsFilter.StorProcParam[1];

            spp[0] = f2.StorProcParamIns("@arch", SqlDbType.VarChar, 20, "jhjhjh");

            SqlCommand myCommand = new SqlCommand();
            myCommand = f2.StorProc(myCommand, conn, "pas_AllDrugsSel", spp);

            if (dt_drugs == null)
            {
                try
                {
                    if (conn.State == ConnectionState.Closed) conn.Open();
                    dt_drugs = new DataTable();
                    dt_drugs.Load(myCommand.ExecuteReader());
                    foreach (DataColumn dc in dt_drugs.Columns)
                    {
                        if (dc.ColumnName != namechcol) dc.ReadOnly = true;
                        else dc.ReadOnly = false;
                    }
                    dt_brand = new DataTable();
                    dt_brand.Load(GetBrandTree(conn));
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                conn.Close();
                f2.rb = true;
            }
            if (dt_drug_tmp == null)
            {
                try
                {
                    if (conn.State == ConnectionState.Closed) conn.Open();
                    dt_drug_tmp = new DataTable();
                    dt_drug_tmp.Load(myCommand.ExecuteReader());
                    foreach (DataColumn dc in dt_drug_tmp.Columns)
                    {
                        if (dc.ColumnName != namechcol) dc.ReadOnly = true;
                        else dc.ReadOnly = false;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                conn.Close();
            }
            f2.sqlconn = conn;
            f2.namechcol = namechcol;
            f2.dt_drug = dt_drugs;
            f2.dt_drug_tmp = dt_drug_tmp;
            if (dt_drug_tmp.Rows.Count == 0)
                f2.dataGridView1.DataSource = f2.dt_drug.DefaultView;
            else
                f2.dataGridView1.DataSource = f2.dt_drug_tmp.DefaultView;
            f2.dt_br = dt_brand;
            f2.ShowDialog();
            listBox1.Items.Clear();
            foreach (DataRow dr in dt_drug_tmp.Rows)
            {
                if (Convert.ToBoolean(dr[namechcol]) == true && dr.RowState != DataRowState.Deleted) listBox1.Items.Add(dr["Товар"]);
            }
            if (listBox1.Items.Count == 0) listBox1.Items.Add("(Все товары)");
            f2.Close();

        }

        private void ChildForm_Load(object sender, EventArgs e)
        {
            conn.ConnectionString = @"Server=" + GetServ("serv.txt") + ";Database=PharmOLAPDW;Integrated Security=True";
            conf = new SqlConnection(@"Server=" + GetServ("serv.txt") + ";Database=SecurityFA;Integrated Security=True");
            listBox1.Items.Add("(Все товары)");
            listBox3.Items.Add("(Все аптеки)");
            checkBox1.Checked = true;
            checkBox3.Checked = true;
            guid = Guid.NewGuid();
            dataGridView1.DataSource = dt_rep.DefaultView;
            dateTimePicker1.Value = DateTime.Now.Date.AddDays(-1);
            if (conf.State == ConnectionState.Closed) conf.Open();
            SqlCommand comf = conf.CreateCommand();
            comf.CommandType = CommandType.StoredProcedure;
            comf.CommandText = "FolderDefaultSel";
            comf.Parameters.AddWithValue("@tool", ToolName);
            DataTable dt_folder = new DataTable();
            dt_folder.Load(comf.ExecuteReader());
            if (dt_folder.Rows.Count > 0) folder = dt_folder.Rows[0]["Folder"].ToString();
            SqlCommand em = conf.CreateCommand();
            em.CommandType = CommandType.StoredProcedure;
            em.CommandText = "pas_EmailUser";
            DataTable dt_mail = new DataTable();
            dt_mail.Load(em.ExecuteReader());
            textBox2.Text = dt_mail.Rows[0][0].ToString();
            checkBox11.Checked = false;
            row_flag = 0;
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked) listBox1.Enabled = true;
            else listBox1.Enabled = false;
        }

        private void checkBox3_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox3.Checked) listBox3.Enabled = true;
            else listBox3.Enabled = false;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            dataGridView1.DataSource = null;
            dt_rep.Clear();
            dt_rep = null;
            dt_rep = new DataTable();
            del = new Deleg(CreateRep);
            this.Text += " Формируется";
            IAsyncResult asyncRes = del.BeginInvoke(new AsyncCallback(CallBackFunc), null); //
            panel1.Enabled = false;
            dataGridView1.Enabled = false;
            //CreateRep();
        }

        private void CallBackFunc(IAsyncResult aRes)
        {
            del.EndInvoke(aRes);
            panel1.Invoke((Func<bool>)(() => panel1.Enabled = true));
            dataGridView1.Invoke((Func<bool>)(() => dataGridView1.Enabled = true));
            this.Invoke((Func<string>)(() => this.Text = this.Text.Replace(" Формируется", "")));
            dataGridView1.Invoke((Func<object>)(() => dataGridView1.DataSource = dt_rep.DefaultView));
        }

        private void CreateRep()
        {
            if (conn.State == ConnectionState.Closed) conn.Open();
            if (dt_pharm == null)
            {
                SqlCommand myCommand = conn.CreateCommand();
                myCommand.CommandType = CommandType.StoredProcedure;
                myCommand.CommandText = @"pas_PharmSel";
                if (conn.State == ConnectionState.Closed) conn.Open();
                dt_pharm = new DataTable();
                dt_pharm.Load(myCommand.ExecuteReader());
                foreach (DataColumn dc in dt_pharm.Columns)
                {
                    if (dc.ColumnName != namechcol) dc.ReadOnly = true;
                    else dc.ReadOnly = false;
                }
                conn.Close();
            }
            try
            {
                dt_ph_code = new DataTable();
                dt_ph_name = new DataTable();
                dt_ph_name.Columns.Add("Город");
                dt_ph_name.Columns.Add("Код аптеки");
                dt_ph_name.Columns.Add("Аптека");
                dt_ph_code.Columns.Add();
                dt_ph_code.Columns.Add();
                dt_ph_code.Columns.Add();
                              
                SqlCommand myCommand = conn.CreateCommand();
                myCommand.CommandType = CommandType.StoredProcedure;
                myCommand.CommandText = @"pas_GuidNatureCodeINS";
                myCommand.Parameters.Add("@guid", SqlDbType.UniqueIdentifier);
                myCommand.Parameters.Add("@code", SqlDbType.Int);
                myCommand.Parameters.Add("@del", SqlDbType.Bit);
                myCommand.Parameters.Add("@nature", SqlDbType.VarChar, 5);

                if (conn.State == ConnectionState.Closed) conn.Open();

                myCommand.Parameters["@guid"].Value = guid;
                myCommand.Parameters["@code"].Value = null;
                myCommand.Parameters["@del"].Value = true;
                myCommand.Parameters["@nature"].Value = null;
                myCommand.ExecuteNonQuery();

                guid = Guid.NewGuid();

                if (dt_drug_tmp != null)
                    if (checkBox1.Checked)
                        foreach (DataRow dr in dt_drug_tmp.Rows)
                            if (Convert.ToBoolean(dr[namechcol]) == true)
                            {
                                myCommand.Parameters["@guid"].Value = guid;
                                myCommand.Parameters["@code"].Value = Convert.ToInt32(dr["Код"]); ;
                                myCommand.Parameters["@del"].Value = false;
                                myCommand.Parameters["@nature"].Value = "drug";
                                myCommand.ExecuteNonQuery();
                            }

                if (dt_pharm != null)
                    if (checkBox3.Checked)
                        foreach (DataRow dr in dt_pharm.Rows)
                            if (Convert.ToBoolean(dr[namechcol]) == true)
                            {
                                myCommand.Parameters["@guid"].Value = guid;
                                myCommand.Parameters["@code"].Value = Convert.ToInt32(dr["Код"]); ;
                                myCommand.Parameters["@del"].Value = false;
                                myCommand.Parameters["@nature"].Value = "pharm";
                                myCommand.ExecuteNonQuery();
                            }
                dt_rep.Clear();
                dt_rep.Load(RepProc(guid, conn, dateTimePicker1,Convert.ToInt32(textBox1.Text),checkBox2.Checked,checkBox4.Checked,checkBox5.Checked,checkBox6.Checked,checkBox7.Checked,checkBox8.Checked, row_flag));
                //dataGridView1.DataSource = dt_rep.DefaultView;

                myCommand.Parameters["@guid"].Value = guid;
                myCommand.Parameters["@code"].Value = null;
                myCommand.Parameters["@del"].Value = true;
                myCommand.Parameters["@nature"].Value = null;
                myCommand.ExecuteNonQuery();

                //conn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                //conn.Close();
            }
        }

        private SqlDataReader RepProc(Guid id, SqlConnection sqlcon, DateTimePicker dtp1, int count, bool arch, bool ph, bool dr, bool az, bool db, bool part, int row)
        {
            SqlCommand sqlcom = sqlcon.CreateCommand();
            sqlcom.CommandType = CommandType.StoredProcedure;
            sqlcom.CommandText = @"pas_DrugsMovement";
            sqlcom.CommandTimeout = 600;

            sqlcom.Parameters.Add("@guid", SqlDbType.UniqueIdentifier);
            sqlcom.Parameters["@guid"].Value = id;

            sqlcom.Parameters.Add("@dt_befpur_beg",SqlDbType.Date);
            sqlcom.Parameters["@dt_befpur_beg"].Value = dtp1.Value;

            sqlcom.Parameters.Add("@countd", SqlDbType.Int);
            sqlcom.Parameters["@countd"].Value = count;

            sqlcom.Parameters.Add("@arch", SqlDbType.Bit);
            sqlcom.Parameters["@arch"].Value = arch;
     
            sqlcom.Parameters.Add("@ph_view", SqlDbType.Bit);
            sqlcom.Parameters["@ph_view"].Value = ph;

            sqlcom.Parameters.Add("@dr_view", SqlDbType.Bit);
            sqlcom.Parameters["@dr_view"].Value = dr;

            sqlcom.Parameters.Add("@az_view", SqlDbType.Bit);
            sqlcom.Parameters["@az_view"].Value = az;

            sqlcom.Parameters.Add("@daysbal_view", SqlDbType.Bit);
            sqlcom.Parameters["@daysbal_view"].Value = db;

            sqlcom.Parameters.Add("@partnotmov", SqlDbType.Bit);
            sqlcom.Parameters["@partnotmov"].Value = part;

            sqlcom.Parameters.Add("@row", SqlDbType.Int);
            sqlcom.Parameters["@row"].Value = row;

            return sqlcom.ExecuteReader();
        }

        private SqlDataReader GetBrandTree(SqlConnection sqlcon)
        {
            SqlCommand com = sqlcon.CreateCommand();
            com.CommandType = CommandType.StoredProcedure;
            com.CommandText = @"pas_BrandTreeSel";

            return com.ExecuteReader();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                PharmFilter.PharmFilter f3 = new PharmFilter.PharmFilter();

                if (dt_pharm == null)
                {
                    SqlCommand myCommand = conn.CreateCommand();
                    myCommand.CommandType = CommandType.StoredProcedure;
                    myCommand.CommandText = @"pas_PharmSel";
                    if (conn.State == ConnectionState.Closed) conn.Open();
                    dt_pharm = new DataTable();
                    dt_pharm.Load(myCommand.ExecuteReader());
                    foreach (DataColumn dc in dt_pharm.Columns)
                    {
                        if (dc.ColumnName != namechcol) dc.ReadOnly = true;
                        else dc.ReadOnly = false;
                    }
                    conn.Close();
                }
                f3.namechcol = namechcol;
                f3.Text = "Фильтр по аптекам";
                f3.sortcoumn = "Аптека";
                f3.dataGridView1.DataSource = dt_pharm.DefaultView;
                f3.ShowDialog();
                listBox3.Items.Clear();
                foreach (DataRow dr in dt_pharm.Rows)
                {
                    if (Convert.ToBoolean(dr[namechcol]) == true) listBox3.Items.Add(dr[f3.sortcoumn]);
                }
                if (listBox3.Items.Count == 0) listBox3.Items.Add("(Все аптеки)");
                f3.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

        private void button5_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.FileName = "товар без движения";
            sfd.Filter = "Файл CSV | *.csv";
            if (sfd.ShowDialog() == DialogResult.OK)
            {   
                SaveDGVToCSVfile(sfd.FileName.ToString(), dataGridView1, true);
            }
        }

        public static bool SaveDGVToCSVfile(string filename, DataGridView table, bool openInExcel)
        {
            try
            {
                StreamWriter sw = new StreamWriter(filename, false, Encoding.Unicode);

                List<int> col_n = new List<int>();
                foreach (DataGridViewColumn col in table.Columns)
                    if (col.Visible)
                    {
                        sw.Write(col.HeaderText + "\t");
                        col_n.Add(col.Index);
                    }
                sw.WriteLine();
                int x = table.RowCount;
                if (table.AllowUserToAddRows) x--;

                for (int i = 0; i < x; i++)
                {
                    for (int y = 0; y < col_n.Count; y++)
                        sw.Write(table[col_n[y], i].Value + "\t");
                    sw.Write(" \r\n");
                }
                sw.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return false;
            }

            if (openInExcel)
            {
                try
                {
                    Process newProc = Process.Start("excel.exe", "\"" + filename + "\"");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
            }
            return true;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //- Сформировать файл для аптек
            try
            {
                dt_ph_name.Clear();
                foreach (DataRow dr in dt_pharm.Rows)
                {
                    if (Convert.ToBoolean(dr[namechcol]))
                    {
                        dt_ph_name.Rows.Add(dr[11],dr[1], dr[2]);
                    }
                }
                if (dt_ph_name.Rows.Count == 0)
                {
                    foreach (DataRow dr in dt_pharm.Rows)
                    {
                        dt_ph_name.Rows.Add(dr[11], dr[1], dr[2]);
                    }
                }

                if (dt_rep != null)
                {
                    DataView view = new DataView(dt_ph_name);
                    DataTable distinctValues = view.ToTable(true, "Город","Код аптеки", "Аптека");
                    
                    DataRow r_dV = distinctValues.Rows[0];

                    foreach (DataRow row_ph in distinctValues.Rows)
                    {
                        CreateExcelDrugMov("Товар без движения " + row_ph["Аптека"] + " " + DateTime.Now.Date.ToShortDateString(), dataGridView1, Convert.ToInt32(row_ph["Код аптеки"]));
                    }

                    MessageBox.Show("Файлы сохранены\nПапка:\n" + folder);
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void button6_Click(object sender, EventArgs e)
        {
            //- Отправить файлы по аптекам
            int send1 = 0;
            try
            {
                DownloadPharmemail();
                dt_ph_name.Clear();
                foreach (DataRow dr in dt_pharm.Rows)
                {
                    if (Convert.ToBoolean(dr[namechcol]))
                    {
                        dt_ph_name.Rows.Add(dr[11],dr[1], dr[2]);
                    }
                }
                DataView view = new DataView(dt_ph_name);
                DataTable distinctValues = view.ToTable(true, "Город", "Код аптеки", "Аптека");
                DataView viewPrice = new DataView(dt_rep);
                DataRow r_dV = distinctValues.Rows[0];
                
                string file;
                foreach (DataRow row_ph in distinctValues.Rows)
                {
                    file = CreateExcelDrugMov("Товар без движения " + row_ph["Аптека"] + " " + DateTime.Now.Date.ToShortDateString(), dataGridView1, Convert.ToInt32(row_ph["Код аптеки"]));
                    foreach (DataRow email in dt_email.Rows)
                    {
                        if (Convert.ToInt32(email["Код аптеки"]) == Convert.ToInt32(row_ph["Код аптеки"]))
                        {
                            SendMail("192.168.0.9", textBox2.Text, "", email[2].ToString(), "Товар без движения " + row_ph["Аптека"].ToString() + " " + DateTime.Now.Date.ToShortDateString(), "Добрый день", file, false);
                            //SendMail("192.168.0.9", "mgushina@apteka-rayona.ru", "", "mgushina@apteka-rayona.ru", "Товар без движения " + row_ph["Аптека"].ToString() + " " + DateTime.Now.Date.ToShortDateString(), "Добрый день", file, false);
                            send1++;
                        }
                    }
                    if (checkBox10.Checked) File.Delete(file);
                }
                MessageBox.Show("Всего отправлено писем: "+send1);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Письма не отправлены "+ ex.ToString());
            }
        }

        private static void SendMail(string smtpServer, string from, string password, string mailto, string caption, string message, string attachFile, bool del)
        {
            try
            {
                MailMessage mail = new MailMessage();
                mail.From = new MailAddress(from);
                mail.To.Add(new MailAddress(mailto));
                mail.CC.Add(new MailAddress(from));
                mail.Subject = caption;
                mail.Body = message;
                if (!string.IsNullOrEmpty(attachFile))
                    mail.Attachments.Add(new Attachment(attachFile));
                SmtpClient client = new SmtpClient();
                client.Host = smtpServer;
                client.Port = 587;
                client.UseDefaultCredentials = true;
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.Send(mail);
                mail.Dispose();
                if (!string.IsNullOrEmpty(attachFile) && del) File.Delete(attachFile);
            }
            catch (Exception e)
            {
                throw new Exception("Mail.Send: " + e.Message);
            }
        }


        private string CreateExcelDrugMov(string filename, DataGridView dgv, int pharmcode)
        {

            if (dgv.DataSource != null && filename != "")
            {
                try
                {
                    if (!checkBox9.Checked)
                    {
                        FolderBrowserDialog folder_d = new FolderBrowserDialog();
                        folder_d.SelectedPath = folder;
                        folder_d.ShowNewFolderButton = true;
                        if (folder_d.ShowDialog() == DialogResult.OK && folder_d.SelectedPath != folder)
                            folder = folder_d.SelectedPath;
                    }
                    if (folder == "")
                        filename = System.Windows.Forms.Application.StartupPath + "\\" + filename + ".xls"; //xlsx
                    else filename = folder + "\\" + filename + ".xls"; //".xlsx"

                    Hashtable myHashtable = new Hashtable();
                    myHashtable = CheckExcellProcesses(myHashtable);

                    Excel.Application exapp = new Excel.ApplicationClass();
                    Excel.Workbook exwb = exapp.Workbooks.Add(System.Reflection.Missing.Value);
                    Excel.Worksheet exws = (Excel.Worksheet)exwb.Sheets[1];

                    foreach (DataGridViewColumn col in dgv.Columns)
                    {
                        exapp.Cells[1, col.Index + 1] = col.Name;
                        exapp.get_Range(exapp.Cells[1, col.Index + 1], exapp.Cells[1, col.Index + 1]).Borders.Color = Excel.XlRgbColor.rgbBlack;
                        exapp.get_Range(exapp.Cells[1, col.Index + 1], exapp.Cells[1, col.Index + 1]).Cells.Interior.Color = Excel.XlRgbColor.rgbGrey;
                    }
                    int r_ind = 2;
                    bool fl = false;
                    foreach (DataGridViewRow row in dgv.Rows)
                    {
                        fl = false;
                        foreach (DataGridViewCell cell in row.Cells)
                        {
                            if (Convert.ToInt32(row.Cells["Код аптеки"].Value) == pharmcode)
                            {
                                exapp.Cells[r_ind, cell.ColumnIndex + 1] = cell.Value;
                                exapp.get_Range(exapp.Cells[r_ind, cell.ColumnIndex + 1], exapp.Cells[r_ind, cell.ColumnIndex + 1]).Borders.Color = Excel.XlRgbColor.rgbBlack;
                                fl = true;
                            }
                        }
                        if (fl) r_ind++;
                    }
                    MessageBox.Show("Имя файла " + filename.ToString());
                    exwb.SaveAs(filename,
                        Excel.XlFileFormat.xlWorkbookNormal, null, null, null, null,
                        Excel.XlSaveAsAccessMode.xlExclusive, null, null, null, null, null);
                    exwb.Close(Type.Missing, Type.Missing, Type.Missing);
                    exapp.Quit();
                    KillExcel(myHashtable);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + " " + ex.Data);
                }
            }
            else return "";
            return filename;
        }

        private void button8_Click(object sender, EventArgs e)
        {
            //- Сохранение папки по умолчанию
            try
            {
                SqlCommand emins = conf.CreateCommand();
                emins.CommandType = CommandType.StoredProcedure;
                emins.CommandText = "pas_EmailUpd";
                emins.Parameters.AddWithValue("@email", textBox1.Text);
                if (conf.State == ConnectionState.Closed) conf.Open();
                emins.ExecuteNonQuery();
                MessageBox.Show("Адрес электронной почты обновлен");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            //- Изменить папку по умолчанию
            try
            {
                FolderBrowserDialog folder_d = new FolderBrowserDialog();
                folder_d.SelectedPath = folder;
                folder_d.ShowNewFolderButton = true;
                if (folder_d.ShowDialog() == DialogResult.OK && folder_d.SelectedPath != folder)
                {
                    if (conf.State == ConnectionState.Closed) conf.Open();
                    SqlCommand comf = conf.CreateCommand();
                    comf.CommandType = CommandType.StoredProcedure;
                    comf.CommandText = "FolderDefaulInsUpd";
                    comf.Parameters.AddWithValue("@tool", ToolName);
                    comf.Parameters.AddWithValue("folder", folder_d.SelectedPath);
                    comf.ExecuteNonQuery();
                    folder = folder_d.SelectedPath;
                    MessageBox.Show("Путь по умолчанию изменен на\n" + folder);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void checkBox11_CheckedChanged(object sender, EventArgs e)
        {
            //- Учитывать товар на реализацию
            if (checkBox11.Checked == true)
            {
                row_flag = 1;
            }
            else
            {
                row_flag = 0;
            }
        }
    }
}
